<template>
  <div class="system-role-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><Avatar /></el-icon>
            角色权限管理
          </span>
          <el-button 
            v-permission="'role.create'" 
            type="primary" 
            :icon="Plus" 
            @click="handleAdd"
          >
            添加角色
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchForm.search"
          placeholder="搜索角色名称、描述"
          style="width: 300px"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <el-select
          v-model="searchForm.is_active"
          placeholder="角色状态"
          clearable
          style="width: 150px; margin-left: 10px"
          @change="handleSearch"
        >
          <el-option label="启用" value="true" />
          <el-option label="禁用" value="false" />
        </el-select>

        <el-button type="primary" :icon="Search" @click="handleSearch" style="margin-left: 10px">
          搜索
        </el-button>
        <el-button :icon="RefreshRight" @click="handleReset">重置</el-button>
      </div>

      <!-- 调试信息 -->
      <el-alert 
        v-if="roleList.length === 0 && !loading" 
        title="提示" 
        type="info" 
        :closable="false"
        style="margin-top: 20px"
      >
        当前没有角色数据，请点击"添加角色"创建第一个角色
      </el-alert>
      
      <div style="margin-top: 10px; color: #999; font-size: 12px;">
        调试信息: 已加载 {{ roleList.length }} 个角色，总数 {{ pagination.total }}
      </div>

      <!-- 角色列表 -->
      <el-table 
        :data="roleList" 
        v-loading="loading"
        border
        stripe
        style="margin-top: 20px"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" min-width="150" />
        <el-table-column prop="description" label="角色描述" min-width="200" />
        <el-table-column label="权限数量" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.permissions?.length || 0 }} 项</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="user_count" label="用户数量" width="120">
          <template #default="{ row }">
            <el-tag type="info">{{ row.user_count }} 人</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.is_active ? 'success' : 'danger'">
              {{ row.is_active ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="160">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button 
              v-permission="'role.edit'" 
              link 
              type="primary" 
              size="small" 
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              v-permission="'role.view'" 
              link 
              type="info" 
              size="small" 
              @click="handleViewPermissions(row)"
            >
              权限
            </el-button>
            <el-button 
              v-permission="'role.delete'" 
              link 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input 
            v-model="roleForm.description" 
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述" 
          />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="roleForm.is_active" />
        </el-form-item>
        <el-form-item label="权限配置">
          <el-tree
            ref="permissionTreeRef"
            :data="permissionOptions"
            show-checkbox
            node-key="value"
            :props="{ children: 'children', label: 'label' }"
            :default-checked-keys="roleForm.permissions"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看权限对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="角色权限详情"
      width="500px"
    >
      <div v-if="currentRole">
        <h4>{{ currentRole.name }}</h4>
        <p style="color: #999; margin-bottom: 20px">{{ currentRole.description }}</p>
        <el-divider />
        <div v-if="currentRole.permissions && currentRole.permissions.length > 0">
          <el-tag 
            v-for="perm in currentRole.permissions" 
            :key="perm"
            style="margin: 5px"
          >
            {{ getPermissionLabel(perm) }}
          </el-tag>
        </div>
        <el-empty v-else description="暂无权限配置" :image-size="100" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Avatar, Plus, Search, RefreshRight } from '@element-plus/icons-vue'
import { getRoleList, createRole, updateRole, deleteRole } from '@/api/system'

// 权限选项树（示例数据）
const permissionOptions = [
  {
    label: '用户管理',
    value: 'user',
    children: [
      { label: '查看用户', value: 'user.view' },
      { label: '创建用户', value: 'user.create' },
      { label: '编辑用户', value: 'user.edit' },
      { label: '删除用户', value: 'user.delete' }
    ]
  },
  {
    label: '角色管理',
    value: 'role',
    children: [
      { label: '查看角色', value: 'role.view' },
      { label: '创建角色', value: 'role.create' },
      { label: '编辑角色', value: 'role.edit' },
      { label: '删除角色', value: 'role.delete' }
    ]
  },
  {
    label: '系统配置',
    value: 'config',
    children: [
      { label: '查看配置', value: 'config.view' },
      { label: '修改配置', value: 'config.edit' }
    ]
  },
  {
    label: '操作日志',
    value: 'log',
    children: [
      { label: '查看日志', value: 'log.view' },
      { label: '导出日志', value: 'log.export' }
    ]
  }
]

// 搜索表单
const searchForm = reactive({
  search: '',
  is_active: ''
})

// 角色列表
const roleList = ref([])
const loading = ref(false)

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('添加角色')
const isEdit = ref(false)
const submitting = ref(false)
const roleFormRef = ref(null)
const permissionTreeRef = ref(null)

// 权限对话框
const permissionDialogVisible = ref(false)
const currentRole = ref(null)

// 角色表单
const roleForm = reactive({
  id: null,
  name: '',
  description: '',
  permissions: [],
  is_active: true
})

// 表单验证规则
const roleRules = {
  name: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
  description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
}

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true
  
  // 检查Token
  const token = localStorage.getItem('token')
  console.log('当前Token:', token)
  
  try {
    // 过滤掉空参数
    const params = {
      page: pagination.page,
      page_size: pagination.pageSize
    }
    
    // 只添加非空的搜索参数
    if (searchForm.search) params.search = searchForm.search
    if (searchForm.is_active) params.is_active = searchForm.is_active
    
    console.log('请求参数:', params)
    
    const response = await getRoleList(params)
    console.log('API响应:', response)
    console.log('响应类型:', typeof response, Array.isArray(response))
    
    // 处理分页响应
    if (response && response.results) {
      // DRF分页格式
      roleList.value = response.results
      pagination.total = response.count || 0
      console.log('使用分页格式，results:', response.results)
    } else if (Array.isArray(response)) {
      // 数组格式
      roleList.value = response
      pagination.total = response.length
      console.log('使用数组格式')
    } else {
      roleList.value = []
      pagination.total = 0
      console.warn('未知的响应格式:', response)
    }
    
    console.log('最终角色列表:', roleList.value)
    console.log('总数:', pagination.total)
  } catch (error) {
    ElMessage.error('获取角色列表失败: ' + (error.message || '未知错误'))
    console.error('获取角色列表错误:', error)
    console.error('错误详情:', error.response)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchRoleList()
}

// 重置
const handleReset = () => {
  searchForm.search = ''
  searchForm.is_active = ''
  handleSearch()
}

// 添加角色
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加角色'
  Object.assign(roleForm, {
    id: null,
    name: '',
    description: '',
    permissions: [],
    is_active: true
  })
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑角色'
  Object.assign(roleForm, {
    id: row.id,
    name: row.name,
    description: row.description,
    permissions: row.permissions || [],
    is_active: row.is_active
  })
  dialogVisible.value = true
}

// 查看权限
const handleViewPermissions = (row) => {
  currentRole.value = row
  permissionDialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!roleFormRef.value) return
  
  await roleFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    // 获取选中的权限（只获取叶子节点，不包括父节点）
    if (permissionTreeRef.value) {
      roleForm.permissions = permissionTreeRef.value.getCheckedKeys(true)
    }
    
    console.log('提交角色数据:', roleForm)
    console.log('选中的权限（仅叶子节点）:', roleForm.permissions)
    
    submitting.value = true
    try {
      let result
      if (isEdit.value) {
        result = await updateRole(roleForm.id, roleForm)
        console.log('更新角色响应:', result)
        ElMessage.success('更新角色成功')
      } else {
        result = await createRole(roleForm)
        console.log('创建角色响应:', result)
        ElMessage.success('添加角色成功')
      }
      dialogVisible.value = false
      await fetchRoleList()
    } catch (error) {
      console.error('提交角色失败:', error)
      ElMessage.error(error.response?.data?.message || error.message || '操作失败')
    } finally {
      submitting.value = false
    }
  })
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 ${row.name} 吗？`,
      '警告',
      { type: 'error' }
    )
    
    await deleteRole(row.id)
    ElMessage.success('删除成功')
    fetchRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 对话框关闭
const handleDialogClose = () => {
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
}

// 获取权限标签
const getPermissionLabel = (value) => {
  const findLabel = (options) => {
    for (const option of options) {
      if (option.value === value) return option.label
      if (option.children) {
        const label = findLabel(option.children)
        if (label) return label
      }
    }
    return value
  }
  return findLabel(permissionOptions)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString('zh-CN')
}

// 挂载时获取数据
onMounted(() => {
  fetchRoleList()
})
</script>

<style scoped>
.system-role-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header .title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
}

.search-bar {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px 0;
}
</style>

